package com.shanjupay.merchant.service.impl;

import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.QiniuUtils;
import com.shanjupay.merchant.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

/**
 * @author whb
 * @create 2021-11-30 13:04
 * @desciption 文件上传和下载Service实现类
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private ConfigurableApplicationContext applicationContext;

    /**
     * 上传文件
     * @param bytes 上传文件的字节数组
     * @param fileName 文件名
     * @return 文件访问路径（绝对url）
     * @throws BusinessException
     */
    @Override
    public String upload(byte[] bytes, String fileName) throws BusinessException {
        //动态获取Nocas中参数的值
        String qiniuUrl=applicationContext.getEnvironment().getProperty("oss.qiniu.url");
        String accessKey=applicationContext.getEnvironment().getProperty("oss.qiniu.accessKey");
        String secretKey=applicationContext.getEnvironment().getProperty("oss.qiniu.secretKey");
        String bucket=applicationContext.getEnvironment().getProperty("oss.qiniu.bucket");

        try {
            QiniuUtils.upload2qiniu(accessKey, secretKey, bucket, bytes, fileName);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100106);
        }
        //上传成功后，会犯文件的访问地址（绝对路径）
        return qiniuUrl+fileName;
    }
}
